#ifndef WorkerThread_H_
#define WorkerThread_H_
#include <functional>
#include <stdint.h>
#include <stdio.h>
#include <list>
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <condition_variable>
#include <map>
#include <future>

#include <stdint.h>
#include <string>
#include <vector>


class Timer
{
public:
	Timer(int64_t delay, std::function<bool()> cb) : m_iDelay(delay), m_cb(cb) {};
	~Timer() {};
	int64_t m_iDelay = 0;
	std::function<bool()> m_cb;
	int64_t m_iTimerId = -1;
};

using Task = std::function<void()>; //定义类型


class TaskScheduler
{
public:
	TaskScheduler();

	int32_t StartRun(std::string threadName);
	void StopRun();
	~TaskScheduler();


public:

	// 添加一个定时器
	virtual int64_t AddTimer(int64_t iDelayUs, std::function<bool()> fcb);
	// 删除一个定时器
	virtual int32_t DelTimer(int64_t timerId);

	// 异步任务
	virtual void PostTask(Task task);
	// 同步执行任务
	virtual void InvokTask(Task task);

	std::string GetThreadId();


	//virtual void UpdateChannel(ChannelPtr channel);
	//virtual void RemoveChannel(ChannelPtr& channel);

private:
	void SetThreadName(std::string threadName);
	void RunLoop();
	int64_t getCurrentTicket();

	int64_t flushDelayTask(uint64_t now_time);

	int64_t getMinDelay();

private:
	std::multimap<uint64_t, std::shared_ptr<Timer> > m_delayTask;
	std::mutex _mutex;
	std::condition_variable _condition;
	bool m_bStart = false;
	int64_t m_iTimerId = 0;

	std::list<Task> _queue;

	std::thread* m_loopThread = NULL;
	bool m_bExitThread = false;
	std::thread::id _loopThreadId;
};

class EventLoop
{
public:
	EventLoop(const EventLoop&) = delete;
	EventLoop& operator = (const EventLoop&) = delete;
	EventLoop();  //std::thread::hardware_concurrency()
	virtual ~EventLoop();

	std::shared_ptr<TaskScheduler> GetTaskScheduler();

	int32_t Loop(std::string name_thread,uint32_t num_threads = 1);
	void Quit();

private:
	std::string m_name = "";
	std::mutex mutex_;
	uint32_t num_threads_ = 1;
	uint32_t index_ = 1;
	std::vector<std::shared_ptr<TaskScheduler>> task_schedulers_;

};


class EventLoopMngr
{
protected:
	EventLoopMngr();

public:
	static EventLoopMngr* GetInstance();

	int32_t Init(uint32_t num_threads = 1, std::string name_thread = "Timer");
	int32_t InitRender(uint32_t num_threads = 1, std::string name_thread ="RenderTimer");
	virtual ~EventLoopMngr();

public:

	EventLoop m_oEventLoop;
	// add by zl 这个线程池组用来渲染图像
	EventLoop m_oEventLoopRender;

private:
	static EventLoopMngr *m_oInstance;
	static std::once_flag m_flag;

};

#endif